package com.rankeiot.platform.controller;

import com.rankeiot.core.Current;
import com.rankeiot.core.MenuManager;
import com.rankeiot.core.data.MenuItem;
import com.rankeiot.platform.domain.Menu;

import com.rankeiot.platform.service.MenuService;
import lombok.RequiredArgsConstructor;

import com.rankeiot.core.anno.Auth;
import com.rankeiot.core.inner.argumet.QueryParams;
import com.rankeiot.core.util.CollectionUtil;
import org.sagacity.sqltoy.dao.LightDao;
import com.rankeiot.core.data.response.Resp;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.rankeiot.platform.PlatformMenu;
import com.rankeiot.core.sqltoy.Sql;


import jakarta.validation.Valid;

import java.util.List;

/**
 * 系统菜单
 */
@Tag(name = "系统菜单")
@Auth
@RestController
@RequestMapping("menu")
@RequiredArgsConstructor
public class MenuController {

    final LightDao dao;
    final MenuService menuService;
    /**
     * 新增系统菜单
     */
    @Operation(summary = "新增系统菜单")
    @Auth(PlatformMenu.MENU_ADD)
    @PostMapping("add")
    public Resp add(@Valid @RequestBody Menu menu) {
        dao.save(menu);
        MenuManager.addMenu(menu.getMenuGroup(),menu.createItem());
        cleanUserMenuCache();
        return Resp.ok();
    }

    /**
     * 删除系统菜单
     */
    @Operation(summary = "删除系统菜单")
    @Auth(PlatformMenu.MENU_DELETE)
    @Transactional
    @PostMapping("delete")
    public Resp delete(String id,String menuGroup) {
        // dao.loadAll(menus);
       Menu menu=dao.load(new Menu(id,menuGroup));
        if(menu==null){
            Resp.fail("删除失败");
        }
        dao.executeSql("delete from "+Menu.TABLE+" where id=:id OR parent like concat(:id,'%')",menu);
        menuService.reloadMenu();
        cleanUserMenuCache();
        return Resp.ok();
    }

    /**
     * 重置菜单
     */
    @Operation(summary = "重置菜单")
    @Auth(PlatformMenu.MENU_EDIT)
    @PostMapping("reset")
    @Transactional
    public Resp rest(){
       // menuService.reloadMenu();
        //删除原来的系统菜单
        dao.executeSql("delete from "+Menu.TABLE+" where `system`=true");
        //同步内置菜单
        menuService.syncMenu();
        //清除用户菜单选项
        cleanUserMenuCache();
        return Resp.ok();
    }
    /**
     * 更新系统菜单
     */
    @Operation(summary = "更新系统菜单")
    @Auth(PlatformMenu.MENU_EDIT)
    @PostMapping("save")
    public Resp save(@Valid @RequestBody Menu menu) {
        dao.update(menu);
        MenuItem m=MenuManager.getMenuItem(menu.getMenuGroup(),menu.getId());
        m.setIcon(menu.getIcon());
        m.setTitle(menu.getTitle());
        m.setEnable(menu.getEnable());
        m.setOrder(menu.getSort());
        m.setPath(menu.getPath());
        cleanUserMenuCache();
        return Resp.ok();
    }

    /**
     * 获取系统菜单
     */
    @Operation(summary = "获取系统菜单详细")
    @Auth(PlatformMenu.MENU)
    @GetMapping("detail")
    public Resp<Menu> detail(String id,String menuGroup) {
        Menu menu = dao.load(new Menu(id,menuGroup));
        return Resp.of(menu);
    }

    /**
     * 获取系统菜单列表
     */
    @Operation(summary = "列出系统菜单")
    @Auth(PlatformMenu.MENU)
    @PostMapping("list")
    public Resp<List<Menu>> list(QueryParams query) {
        String sql = Sql.select("*")
                .from(Menu.TABLE)
                .eq(Menu.Fields.menuGroup)
                .optional(s->s.eq(Menu.Fields.menuType))
                .orderBy(Menu.Fields.sort.name())
                .toString();
        List<Menu> result = dao.find(sql, query.params(), Menu.class);
        return Resp.of(result);
    }

    @Operation(summary = "修改图标")
    @Auth(PlatformMenu.MENU_EDIT)
    @PostMapping("updateIcon")
    public Resp updateIcon(@RequestBody Menu menu) {
        String icon = menu.getIcon();
        menu = dao.load(menu);
        if (menu == null) {
            Resp.fail("更新失败");
        }
        menu.setIcon(icon);
        dao.update(menu);
        MenuItem item = MenuManager.getMenuItem(menu.getMenuGroup(),menu.getId());
        item.setIcon(icon);
        cleanUserMenuCache();
        return Resp.of(icon);
    }

    @Operation(summary = "切换图标")
    @Auth(PlatformMenu.MENU_EDIT)
    @PostMapping("switchMenu")
    public Resp switchMenu(String id,String menuGroup) {
        Menu menu = new Menu(id,menuGroup);
        menu = dao.load(menu);
        if (menu == null) {
            Resp.fail("切换失败");
        }
        menu.setEnable(!menu.getEnable());
        dao.update(menu);
       // menuService.reloadMenu();
        MenuItem item = MenuManager.getMenus(menu.getMenuGroup()).get(menu.getId());
        item.setEnable(menu.getEnable());
        cleanUserMenuCache();
        return Resp.ok();
    }
    @Auth(PlatformMenu.MENU_EDIT)
    @PostMapping("changeSort")
    public Resp changeSort(@RequestBody List<Menu> menus){
        dao.updateAll(menus);
        menuService.reloadMenu();
        cleanUserMenuCache();
        return Resp.ok();
    }
    /**
     * 清理用户菜单缓存，这里把缓存用户全部清除，用户数据会根据token重建
     */
    private void cleanUserMenuCache(){
        Current.invalidateAllUser();
    }
}
